#include "dkglBezier.h"
//#include "dkglLog.h"

namespace DKGL
{
	
CubicBezierCurve::CubicBezierCurve() : LineStrip(10)
{
	mResolution = 10;
}

CubicBezierCurve::CubicBezierCurve(const Vector3& p1, const Vector3& p2, const Vector3& p3, const Vector3& p4)
: LineStrip(10)
{
	mResolution = 10;
	mCtrlPt[0] = p1; mCtrlPt[1] = p2; mCtrlPt[2] = p3; mCtrlPt[3] = p4;
	_updateVertBuf();
}
	
CubicBezierCurve::CubicBezierCurve(const CubicBezierCurve& cbc) : LineStrip(cbc.seg())
{
	for(int i=0;i<4;i++)
		mCtrlPt[i] = cbc.mCtrlPt[i];

	mResolution = cbc.mResolution;
	_updateVertBuf();
	
}

CubicBezierCurve::~CubicBezierCurve()
{

}
	
void CubicBezierCurve::setResolution(int res)
{
	mResolution = res;
	resetSize(10, mResolution);
	_updateVertBuf();
}
	
Vector3 CubicBezierCurve::paramVal(float t)
{
	/*if(t<0||t>1)
		g_Log.dump("param out of range", __FILE__, __LINE__);*/
	
	Vector3 vec;
	for(int i=0;i<3;i++)
	{
		vec.val[i] = mCtrlPt[0].val[i]*pow(1-t, 3) + 3*t*pow(1-t, 2)*mCtrlPt[1].val[i] + 
			3*pow(t, 2)*(1-t)*mCtrlPt[2].val[i] + pow(t, 3)*mCtrlPt[3].val[i];
	}

	return vec;
}

void CubicBezierCurve::setCtrlPt(Vector3* ctrlPt)
{
	for(int i=0;i<4;i++)
		mCtrlPt[i] = ctrlPt[i];
}

void CubicBezierCurve::setCtrlPt1(const Vector3& p)
{
	mCtrlPt[0] = p;
	_updateVertBuf();
}

void CubicBezierCurve::setCtrlPt2(const Vector3& p)
{
	mCtrlPt[1] = p;
	_updateVertBuf();
}

void CubicBezierCurve::setCtrlPt3(const Vector3& p)
{
	mCtrlPt[2] = p;
	_updateVertBuf();
}

void CubicBezierCurve::setCtrlPt4(const Vector3& p)
{
	mCtrlPt[3] = p;
	_updateVertBuf();
}

void CubicBezierCurve::_updateVertBuf()
{
	Vector3 vec;
	float t;
	int seg, i;

	seg = this->seg();

	for(i=0;i<=seg;i++)
	{
		t = static_cast<float>(i)/seg;
		vec = paramVal(t);
		setXYZ(i, vec.x, vec.y, vec.z);
	}
}

}